package com.bawei.module_mine.ui

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.view.MenuItem
import android.view.View
import android.webkit.*
import android.widget.Toast
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIActivity
import com.bawei.module_mine.databinding.ActivityWebBinding

@Route(path = Router.Ui.WEB_ACTIVITY)
class WebActivity : BaseMVIActivity() {
    private val binding by lazy {
        ActivityWebBinding.inflate(layoutInflater)
    }
    
    @Autowired
    @JvmField
    var url: String = ""

    override fun initView() {
        super.initView()
        ARouter.getInstance().inject(this)
        
        // 设置工具栏
        setupToolbar()
        
        // 配置WebView设置
        setupWebView()
        
        // 设置WebViewClient
        binding.web.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                // 显示加载进度
                binding.progressBar.visibility = View.VISIBLE
                binding.progressBar.progress = 0
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                // 隐藏加载进度
                binding.progressBar.visibility = View.GONE
                // 更新工具栏标题
                view?.title?.let { title ->
                    if (title.isNotEmpty() && title != "about:blank") {
                        binding.toolbar.title = title
                    }
                }
            }

            override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
                // 处理加载错误
                binding.progressBar.visibility = View.GONE
                if (request?.isForMainFrame == true) {
                    Toast.makeText(this@WebActivity, "加载失败，请检查网络连接", Toast.LENGTH_SHORT).show()
                }
            }

            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                // 处理URL跳转
                request?.url?.let { url ->
                    if (url.scheme == "http" || url.scheme == "https") {
                        view?.loadUrl(url.toString())
                        return true
                    }
                }
                return false
            }
        }

        // 设置WebChromeClient
        binding.web.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                // 更新进度条
                binding.progressBar.progress = newProgress
                if (newProgress >= 100) {
                    binding.progressBar.visibility = View.GONE
                }
            }
        }

        // 加载URL
        if (url.isNotEmpty()) {
            binding.web.loadUrl(url)
        } else {
            Toast.makeText(this, "无效的URL", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.apply {
            setDisplayHomeAsUpEnabled(true)
            setDisplayShowHomeEnabled(true)
            title = "用户协议"
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView() {
        val webSettings = binding.web.settings
        
        // 基本设置
        webSettings.javaScriptEnabled = true  // 启用JavaScript
        webSettings.domStorageEnabled = true  // 启用DOM存储
        webSettings.databaseEnabled = true    // 启用数据库
        
        // 缓存设置
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT  // 使用默认缓存模式
//        webSettings.setAppCacheEnabled(true)  // 启用应用缓存
        
        // 渲染设置
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)  // 高优先级渲染
        webSettings.blockNetworkImage = false  // 不阻塞网络图片
        
        // 性能优化
        webSettings.loadsImagesAutomatically = true  // 自动加载图片
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW  // 允许混合内容
        
        // 缩放设置
        webSettings.setSupportZoom(true)  // 支持缩放
        webSettings.builtInZoomControls = true  // 内置缩放控件
        webSettings.displayZoomControls = false  // 不显示缩放控件
        
        // 其他优化
        webSettings.allowFileAccess = true  // 允许文件访问
        webSettings.allowContentAccess = true  // 允许内容访问
        webSettings.loadWithOverviewMode = true  // 自适应屏幕
        webSettings.useWideViewPort = true  // 使用宽视图端口
        
        // 设置用户代理
        webSettings.userAgentString = webSettings.userAgentString + " IVideoApp"
        
        // 硬件加速
        binding.web.setLayerType(View.LAYER_TYPE_HARDWARE, null)
    }

    override fun generateViewModel() {
        // 无需实现
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun handleState() {
        // 无需实现
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    override fun onBackPressed() {
        if (binding.web.canGoBack()) {
            binding.web.goBack()
        } else {
            super.onBackPressed()
        }
    }
    
    override fun onPause() {
        super.onPause()
        binding.web.onPause()
    }
    
    override fun onResume() {
        super.onResume()
        binding.web.onResume()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 清理WebView资源
        binding.web.apply {
            clearHistory()
            clearCache(true)
            loadUrl("about:blank")
            onPause()
            removeAllViews()
            destroy()
        }
    }
}